<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Auth;

class Withdraw extends Model
{
    const STATUS_SUCCESS = 'success';
    const STATUS_CANCEL= 'cancel';
    const STATUS_PROCESSING = 'processing';
    const STATUS_FAILED = 'failed';

    public static function boot() {
        parent::boot();
        
        static::creating(function($model) {
            $model->invoice = self::invoiceGenerator();
        });
    }


    /**
     * 获得店铺。
     */
    public function shop()
    {
        return $this->belongsTo('App\Models\Shop', 'shop_id');
    }

    /**
     * 限制当前店铺
     */
    public function scopeOwnerShop($query)
    {
        return $query->where('shop_id', Auth::guard('shop')->user()->id);
    }

    /**
     * 获取用户的名字。
     *
     * @return string
     */
    public function getStatusLabelAttribute()
    {
        return $this->getStatus($this->attributes['status']);
    }

    /**
     * 提现状态
     *
     * @param String $type
     * @return String
     */
    public static function getStatus($status)
    {
        $statuses = [
            self::STATUS_SUCCESS    => '成功',
            self::STATUS_CANCEL     => '取消',
            self::STATUS_PROCESSING => '正在处理',
            self::STATUS_FAILED     => '失败',
        ];

        if (!empty($status)){
            if (isset($statuses[$status])){
                return $statuses[$status];
            }else{
                return '';
            }
        }

        return $statuses;
    }

    /**
     * 提现流水
     * 
     * @return String
     */
    protected static function invoiceGenerator()
    {
        $microtime = microtime(true) * 10000;
        $number = date('YmdHis') . rand(111, 999) . substr($microtime, -5);
        $flag = self::where('invoice', $number)->count();
        if ($flag > 0){
            $number = self::invoiceGenerator();
        }
        return $number;
    }

}
